﻿using System;
using System.Runtime.CompilerServices;

namespace UtilZ.Dotnet.Ex.Base
{
    /// <summary>
    /// Span扩展类
    /// </summary>
    unsafe public static partial class SpanEx
    {
        /// <summary>
        /// 获取Span数据指向的起始指针
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="span">Span数据</param>
        /// <returns>Span数据指向的起始指针</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static T First<T>(in this Span<T> span)
            where T : struct
        {
            return span[0];
        }

        /// <summary>
        /// 获取Span数据指向的起始指针
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="span">Span数据</param>
        /// <returns>Span数据指向的起始指针</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static T FirstOrDefault<T>(in this Span<T> span)
            where T : struct
        {
            if (span.Length > 0)
            {
                return span[0];
            }
            else
            {
                return default(T);
            }
        }

        /// <summary>
        /// 获取Span数据指向的起始指针
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="span">Span数据</param>
        /// <returns>Span数据指向的起始指针</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static T Last<T>(in this Span<T> span)
            where T : struct
        {
            return span[span.Length - 1];
        }

        /// <summary>
        /// 获取Span数据指向的起始指针
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="span">Span数据</param>
        /// <returns>Span数据指向的起始指针</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static T LastOrDefault<T>(in this Span<T> span)
            where T : struct
        {
            if (span.Length > 0)
            {
                return span[span.Length - 1];
            }
            else
            {
                return default(T);
            }
        }



    }
}
